Thread: malloc() vs buffer[]?

  1. #16
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,674
    Personally, I'd go with option 2 until such time that I could prove option 1 had much better (and needed) performance. If you choose option 1, make sure packet is a member of the struct.

    Copying a few bytes (whether by memcpy or strcpy) is insignificant to the time it took to transmit those bytes over the net, or what other work you have planned later on.

    > unsigned char storageArea[300]; //300 is an expected length
    Or you could have a char pointer (as per case 1) then allocate the exact space you need, then copy the data.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  2. #17
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Simply put, option 1 is a program logic and maintenance nightmare. You have three apparently independent members of the struct all pointing to the same memory area. It becomes very hard to keep track of who is responsible for freeing the memory, and when. It becomes even harder to find it out from the code after forgetting it. (Or the code is then maintained by someone else.)

    So as Salem said, go with option 2 unless you really, really, REALLY need the performance of option 1.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #18
    Registered User
    Join Date
    Jun 2007
    Posts
    13
    Ty! That was the answer I needed Thx a lot

    Krones

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. the basics of malloc
    By nakedBallerina in forum C Programming
    Replies: 21
    Last Post: 05-20-2008, 02:32 AM
  3. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM